# require  socketIO-client-2
from socketIO_client import SocketIO, LoggingNamespace


''' socketio client '''


class SocketIoClient():
 
    def __init__(self, ip, port) -> None:
        self.client = SocketIO(ip, port, LoggingNamespace)
        self.client.on('test_conn', self.on_test_return)
        self.client.on('update', self.on_register_return)
        self.client.on('terminal', self.on_terminal)
        self.client.on('error', self.on_error)
        
        self.client.emit('test_conn')  # 测试连接
        self.client.wait(seconds=1)

    def register(self, taskids):
        msg = str([{"id":id} for id in taskids]).replace('\'', '\"')
        if taskids: self.client.emit('res_client', msg)
        self.client.wait(seconds=0.1)

    def on_register_return(self, *args):
        assert args == ('Your task is registered, please wait...',)
        print('socketio: task register -> ', args[0])

    def on_test_return(self, *args):
        assert args == ('You are connected.',)
        print('socketio: test conn -> ', args[0])

    def on_terminal(self, *args):
        ''' 处理消息日志 '''
        pass
    
    def on_error(self, *args):
        ''' 处理异常'''
        pass

    def close(self):
        if self:
            try:
                self.client.disconnect()
                print('socketio: client close.')
            except Exception as e:
                print('socketio: close error -> ', str(e))

Ip = '123.60.59.68'
Port = 80
client = SocketIoClient(Ip, Port)
client.register(taskids=[111,222])
client.close()

